#include "stdafx.h"


HandBanana::Core::Timer::Timer(float argTimePerTick) : mTimePerTick(argTimePerTick)
{
    //
    // MSDN:
    // The QueryPerformanceFrequency function retrieves the frequency of the
    // high-resolution performance counter, if one exists. The frequency cannot
    // change while the system is running.
    //

    LARGE_INTEGER li = {0};
    
    // TODO: We should have a fallback if the performance counter is not supported
    if (FALSE == ::QueryPerformanceFrequency(&li))
    {
        throw gcnew Exception("Performance timer is not supported.");
    }

    mFrequency = (float)li.QuadPart;
}


void HandBanana::Core::Timer::BeginTiming(void)
{
    LARGE_INTEGER startTime = {0};

    // Query the performance counter for the start time
    ::QueryPerformanceCounter(&startTime);
    mStartTime = startTime.QuadPart;
}


void HandBanana::Core::Timer::EndTiming(void)
{
    // Query the performance counter for the end time
    LARGE_INTEGER endTime = {0};
    ::QueryPerformanceCounter(&endTime);

    // Save the time that we have accumulated
    mAccumulatedTime += (float)(endTime.QuadPart - mStartTime)/mFrequency;
}


void HandBanana::Core::Timer::Reset(void)
{
    mAccumulatedTime = 0;
}


Boolean HandBanana::Core::Timer::Tick(void)
{
    return (mAccumulatedTime >= mTimePerTick);
}